<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>主页</title>
<link rel="stylesheet" href="{{ url_for('static', path='/styles.css') }}">
<link rel="stylesheet" href="{{ url_for('static', path='/floating-btn.css') }}">
</head>
<body>
    <!-- 筛选表单 -->
    <div class="filter-form">
        <div class="filter-item">
            <input type="text" id="rContent" name="rContent" placeholder="请输入关键词">
        </div>
        <button type="button" onclick="fetchData()">搜索</button>
    </div>

    <!-- 数据表格 -->
    <table id="table" class="data-table">
        <thead>
            <tr>
                <th>行号</th>
                <th>房号</th>
                <th>姓名</th>
                <th>租金</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="data-table-body">
            <!-- 数据通过 API 请求动态填充 -->
        </tbody>
    </table>

    <button class="floating-btn" onclick="toggleAddMenu()">
      +
    </button>
    <div class="add-menu" id="addMenu">
      <button class="menu-btn" onclick="openAddTenantForm()">新增入住</button>
      <button class="menu-btn" onclick="openAddHouseForm()">添加房源</button>
      <button class="menu-btn" onclick="openRest(this)">重置 1-15号</button>
      <button class="menu-btn" onclick="openRest(this)">重置 16-31号</button>
    </div>

    <!-- 脚本 -->
    <script>
        window.onload = function() {
            fetch('http://a.efrey.top/wx/rent_count')
                .then(response => response.json())
                .then(data => {
                    const newRow = document.createElement("div");
                    newRow.innerHTML = `${data.result}`
                    document.querySelector(".filter-form").after(newRow);
                })
                .catch(error => console.error('统计查询失败:', error));
        }
      let isMenuOpen = false;

      function toggleAddMenu() {
        const menu = document.getElementById('addMenu');
        isMenuOpen = !isMenuOpen;
        menu.style.display = isMenuOpen ? 'block' : 'none';
      }


      // 添加点击事件监听器
        table.addEventListener('click', function(event) {
          const target = event.target;
          const tr = target.closest('tr');
          if (!tr || tr.classList.contains('expandable') || target.closest('button')) return;
          if (tr) {
              const expandableRow = tr.nextElementSibling;

              // 切换展开/折叠状态
              if (expandableRow.classList.contains('expanded')) {
                  // 如果已经展开，折叠
                  expandableRow.classList.remove('expanded');
              } else {
                  // 如果未展开，展开
                  expandableRow.classList.add('expanded');
              }
          }
      });


        function fetchData() {
            var rContent = document.getElementById('rContent').value;
            // 构建请求参数
            var params = new URLSearchParams({
                rContent: rContent
            });
            const table = document.getElementById('table');

            // 发送 GET 请求到后端 API
            fetch('http://a.efrey.top/wx/filter?' + params)
                .then(response => response.json())
                .then(data => updateTable(data))
                .catch(error => console.error('获取数据失败:', error));
        }

        function updateTable(data) {
            var tableBody = document.getElementById('data-table-body');
            tableBody.innerHTML = ''; // 清空表格

            data.forEach((item, index) => {
                var row = tableBody.insertRow();
                row.setAttribute('data-index', index)
                // var div = tableBody.innerHTML = '';
                var indexCell = row.insertCell(0);
                var addressCell = row.insertCell(1);
                var nameCell = row.insertCell(2);
                var priceCell = row.insertCell(3);
                var statusCell = row.insertCell(4);
                var buttonCell = row.insertCell(5);

                // 设置单元格内容
                indexCell.textContent = item.index;
                addressCell.textContent = item.address;
                nameCell.textContent = item.name;
                priceCell.textContent = item.price;
                statusCell.textContent = item.status;

                // 按钮容器
                buttonCell.classList.add('button-container');

                // 收租按钮
                const rentButton = document.createElement('button');
                rentButton.classList.add('green-button');
                rentButton.textContent = '收租';
                rentButton.onclick = function () {
                    handleRent(item.index, statusCell, rentButton, this.parentElement);
                };

                // 退租按钮
                const releaseButton = document.createElement('button');
                releaseButton.classList.add('red-button');
                releaseButton.textContent = '退租';
                releaseButton.onclick = function () {
                    handleRelease(item.index, row, this.parentElement);
                };

                // 修改按钮
                const modifyButton = document.createElement('button');
                modifyButton.classList.add('blue-button');
                modifyButton.textContent = '修改';
                modifyButton.onclick = function () {
                    handleModify(item.index);
                };

                // 根据状态添加按钮
                if (item.status === '未收租') {
                    statusCell.classList.add('status-not-rented');
                    buttonCell.appendChild(rentButton);
                } else if (item.status === '已收租') {
                    statusCell.classList.add('status-rented');
                    rentButton.style.display = 'none';
                }

                buttonCell.appendChild(modifyButton);
                buttonCell.appendChild(releaseButton);

                // 创建详细信息行，并隐藏
                const expandableRow = document.createElement('tr');
                expandableRow.classList.add('expandable');
                expandableRow.innerHTML = `
                    <td></td>
                    <td colspan="5">
                        <p><strong>电话:</strong> ${item.phone}</p>
                        <p><strong>日期:</strong> ${item.date}</p>
                        <p><strong>备注:</strong> ${item.note}</p>
                    </td>
                `;
                tableBody.appendChild(expandableRow);

                });

        }

        // 收租处理逻辑
        function handleRent(index, statusCell, rentButton, container) {
            var params = new URLSearchParams({ index: index });
            fetch('http://a.efrey.top/wx/rent?' + params)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应状态不佳');
                    }
                    statusCell.textContent = '已收租';
                    statusCell.classList.remove('status-not-rented');
                    statusCell.classList.add('status-rented');
                    rentButton.style.display = 'none';
                })
                .catch(error => console.error('收租失败:', error));
        }

        // 退租处理逻辑
        function handleRelease(index, row, container) {
            if (confirm('确认退租?')) {
                var params = new URLSearchParams({ index: index });
                fetch('http://a.efrey.top/wx/release?' + params)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络响应状态不佳');
                        }
                        row.remove();
                    })
                    .catch(error => console.error('退租失败:', error));
            }
        }

        // 修改处理逻辑
        function handleModify(index) {
            const url = `http://a.efrey.top/wx/tenant_modify.html?index=${index}`;
            window.location.href = url;
        }

        // 添加房源跳转
        function openAddHouseForm(index) {
            const url = 'http://a.efrey.top/wx/new_house.html';
            window.location.href = url;
        }

        // 新增入住跳转
        function openAddTenantForm(index) {
            const url = 'http://a.efrey.top/wx/add_tenant.html';
            window.location.href = url;
        }

        function openRest(button) {
            const text = button.textContent;
            var tableBody = document.getElementById('data-table-body');
            var params = new URLSearchParams({ rContent: text });
            if (confirm(`确认${text}?`)){
                fetch('http://a.efrey.top/wx/rent_reset?' + params)
                .then(response => response.json())
                .then(data => {
                    tableBody.innerHTML = `<div ><h2>${data.result}</h2></div>`;
                })
                .catch(error => console.error('重置失败:', error));
            }
        }

    </script>
</body>
</html>